(function () {
  'use strict';

  angular
    .module('client')
    .controller('ApplyController', ApplyController);

  ApplyController.$inject = ['$uibModalInstance', 'utilService', 'deviceService', 'deviceInfo'];
  function ApplyController($uibModalInstance, utilService, deviceService, deviceInfo) {
    var vm = this;
    vm.deviceInfo = deviceInfo;
    vm.errorMsg = null;
    vm.applyDevice = applyDevice;
    vm.close = close;

    function applyDevice(opts) {
      var localTime = new Date();
      localTime = utilService.timeConvertToServer(localTime);
      deviceService.applyDevice(opts.deviceID, opts.model, opts.duration, localTime)
        .then(
          function (resp) {
            var data = resp.data;
            deviceService.setDeviceModel(data.deviceModel);
            deviceService.setDeviceInfo({
              os: opts.os || 'Android 4.0.0',
              cpu: opts.cpu || '未知',
              cores: opts.cores || '1',
              width: opts.width || '1080',
              height: opts.height || '1980',
              ram: Math.round(opts.ram / (1024 * 1024) ) || '1',
            });
            deviceService.setLocalTime(data.localTime, data.duration);
            $uibModalInstance.close(opts);
          },
          function (error) {
            vm.errorMsg = error.data;
          })
    }

    function close() {
      $uibModalInstance.dismiss('cancel');
    }
  }

}());
